// 全局上下文
import 'dart:convert';
import 'dart:io';

import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:music_player/bean/music_bean.dart';
import 'package:music_player/model/musci_model.dart';
import 'package:music_player/rpc/server/music_rpc_server.dart';
import 'package:music_player/utils/init_util.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tray_manager/tray_manager.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();


class Application extends StatefulWidget {
  final Widget child;
  const Application({super.key, required this.child});

  @override
  State<Application> createState() => _ApplicationState();
}

class _ApplicationState extends State<Application>  with TrayListener{

  @override
  void initState() {
    super.initState();
    debugPrint("hello application");
    _initializeTray();

    // 初始化服务
    _initRpcServer(context);

    initMusicList(context);
  }

  @override
  void dispose() {
    super.dispose();
    // context.read<SocketModel>().disConnect();
    trayManager.removeListener(this);
    _stopRpcServer();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  void _initRpcServer(BuildContext context) async{
    await MusicRpcServer.start(context);
  }
  void _stopRpcServer() async{
    await MusicRpcServer.stop();
  }

  Future<void> _initializeTray() async {

    // 设置托盘图标
    await trayManager.setIcon("images/favicon.ico");

    // 创建托盘菜单项
    List<MenuItem> items = [
      MenuItem(
        key: 'show',
        label: '打开主页',
      ),
      MenuItem(
        key: 'exit',
        label: '退出',
      ),
    ];

    // 设置托盘上下文菜单
    await trayManager.setContextMenu(Menu(items: items));

    // 添加事件监听
    trayManager.addListener(this);
  }

  @override
  void onTrayIconMouseDown() {
    trayManager.popUpContextMenu();
  }

  @override
  void onTrayIconRightMouseDown() {
    trayManager.popUpContextMenu();
  }

  @override
  void onTrayMenuItemClick(MenuItem menuItem) {
    if (menuItem.key == 'show') {
      appWindow.show();
    } else if (menuItem.key == 'exit') {
      trayManager.destroy();
      appWindow.close();
    }
  }

}
